<?php
namespace app\admin\model;
use think\Model;

class Mp extends Model {
    const SESSION_PREFIX = 'weipeter_';
    const SESSION_CUR_MP = 'cur_mp';

    public static function getList() {
        return Mp::all();
    }

    public static function createMp($data) {
        $mp = new Mp();
        if(isset($data['id'])) {
            $ret = $mp->isUpdate()->save($data,['id'=>$data['id']]);

            // 看看目前选中的微信公众号是否需要刷新
            self::flushSelectedMp($data['id']);

            return $ret;
        }else {
            $data['debug'] = 1;
            $data['create_time'] = time();
            $data['interface_token'] = md5(time() . rand() . $data['token']);
            return $mp->save($data);
        }

    }

    protected function getInterfaceAttr($value,$data) {
        return 'http://' . $_SERVER['HTTP_HOST'] . ROOT_URL . '/?s=/interface/' . $data['interface_token'];
    }

    /**
     * 选择目前公众号
     * @param $id
     * @return bool
     */
    public static function selectMp($id) {
        if($mp = Mp::get($id)) {
            session(self::SESSION_CUR_MP,$mp->append(['interface'])->toArray(),Mp::SESSION_PREFIX);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 获取目前公众号
     * @return mixed
     */
    public static function getSelectedMp() {
        return session(self::SESSION_CUR_MP,'',self::SESSION_PREFIX);
    }

    /**
     * @param $need_flush_id int 如果这个id是目前选择公众号的id，那就会刷新，如果null，则刷新当前选中的mp
     */
    public static function flushSelectedMp($need_flush_id = null) {
        $curMp = get_selected_mp();
        if($need_flush_id === null) {
            self::selectMp($curMp['id']);
        }else {
            if($curMp['id'] == $need_flush_id) {
                self::selectMp($need_flush_id);
            }
        }

    }

    /**
     * 取消选择当前公众号
     */
    public static function deselectMp() {
        session(self::SESSION_CUR_MP,null,Mp::SESSION_PREFIX);
    }
}